import { App } from 'vue'

export default {
  install(app: App) {
    // 自定义全局指令
    app.directive('defaultBind', {
      mounted(el, binding) {
        console.log('el', el)
        console.log('binding', binding.value)
      },
    })
    console.dir(app)
    // // 混入（vue2推荐，vue3组合式api暂不常用）
    // app.mixin({
    //   created() {
    //     console.log('created in plugin')
    //   }
    // })
  },
}

export const whatTime = () => {
  const hours = new Date().getHours()
  let message = ''
  if (hours <= 9) {
    message = '早上'
  } else if (hours <= 12) {
    message = '上午'
  } else if (hours <= 18) {
    message = '下午'
  } else {
    message = '晚上'
  }
  return message
}

// 防抖
export const debounce = (fn: any, time: number) => {
  time = time || 200
  // 定时器
  let timer: any = null
  return function (...args) {
    var _this = this
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(function () {
      timer = null
      fn.apply(_this, args)
    }, time)
  }
}

// 当前年月日
export const getTime = () => {
  const currentDate = new Date();
  const year = currentDate.getFullYear();
  const month = currentDate.getMonth() + 1;
  const day = currentDate.getDate();
  return `${year}年${month}月${day}日`
}

// 当前星期
export const getWeek = () => {
  const days = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
  const date = new Date();
  const dayOfWeek = days[date.getDay()];
  return dayOfWeek
}

// 当前时分秒
export const times = (flag: any) => {
  let currentTime = new Date(); // "Mon Sep 30 2019 20:51:28 GMT+0800 (中国标准时间)"
  let hours = currentTime.getHours();
  let minutes = currentTime.getMinutes();
  let seconds = currentTime.getSeconds();
  if (flag == '24') {
    // 24小时制
    return hours + "点" + minutes + "分"
  } else if (flag == '12') {
    // 12小时制
    if(hours > 12) {
      hours -= 12;
    }
    // hours = hours < 10 ? "0" + hours : hours;
    minutes = minutes < 10 ? '0' + minutes : minutes;
    seconds = seconds < 10 ? '0' + seconds : seconds;
    return hours + "点" + minutes + "分"
  }
}

// 节流
export const throttle = (fn: any, time: number) => {
  let timer: any = null
  time = time || 1000
  return function (...args) {
    if (timer) {
      return
    }
    const _this = this
    timer = setTimeout(() => {
      timer = null
    }, time)
    fn.apply(_this, args)
  }
}

//获取URL中的参数
export const getUrlKey = (name: any, url: any) => {
  return (
      decodeURIComponent(
          (new RegExp("[?|&]" + name + "=" + "([^&;]+?)(&|#|;|$)").exec(
              url
          ) || [, ""])[1].replace(/\+/g, "%20")
      ) || null
  )
}

// 判断设备安卓/IOS
export function isAndroid() {
  let u = navigator.userAgent
  let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //g
  let isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
  if (isAndroid) {
      return true
  } else if (isIOS) {
      return false
  }
}

// 获取Cookie数据
export function getCookie(key) {
  var arr = document.cookie.split("; ") //分号加空格分开
  arr.forEach(item => {
      var resArr = item.split("=");
      if (resArr[0] == key) {
          return resArr[1]; //把键所对应的值返回
      }
  });
}

// Loading 已弃用 暂用全局组件loading
import { ElLoading } from 'element-plus'

export const Loading = (time?: number) => {
  const loading = ElLoading.service({
    lock: true,
    background: 'rgba(0, 0, 0, 0.7)'
  })
  if (time) {
    setTimeout(() => {
      loading.close()
    }, time)
    return
  }
  // 不传值默认8秒超时消失
  setTimeout(() => {
    loading.close()
  }, 8000);
}

// 色值转换
// HEX格式转RGB格式:
export const hex2Rgb = (color: any) => {
  color = color.replace('#', '')
  const result = color.match(/../g) || ''
  for (let i = 0; i < 3; i++) {
    result[i] = parseInt(result[i], 16)
  }
  return result.toString()
}
//RGB格式转HEX格式
export const rgb2Hex = (r: any, g: any, b: any) => {
  const hexs: any[] = [Number(r).toString(16), Number(g).toString(16), Number(b).toString(16)]
  for (let i = 0; i < 3; i++) {
    if (hexs[i].length === 1) {
      hexs[i] = '0' + hexs[i]
    }
  }
  const result = '#' + hexs.join('')
  return result
}

/**
 * 字符串转时间戳
 * @param strTime 字符串时间 格式 '2023-02-11 12:00:00'
 * @returns 数字类型的时间戳
 */

export const stringTransformTimeStamp = (strTime: string): number => {
  const _date = new Date(strTime)
  return _date.getTime()
}

/**
 * 时间戳转字符串
 * @param timeStamp 时间戳 格式 1676088000000
 * @returns 字符串时间
 */

export const timeStampTransformstring = (timeStamp: number): string => {
  const _date = new Date(timeStamp)
  const year = _date.getFullYear()
  const month = _date.getMonth() + 1
  const day = _date.getDate()
  const hours = _date.getHours()
  const minutes = _date.getMinutes()
  const seconds = _date.getSeconds()
  const _strTime = `${year}-${month >= 10 ? month : '0' + month}-${day > 10 ? day : '0' + day} ${
    hours > 10 ? hours : '0' + hours
  }:${minutes > 10 ? minutes : '0' + minutes}:${seconds >= 10 ? seconds : '0' + seconds}`
  return _strTime
}

/**
 * 清除文本中的空格
 * @param str 需要格式化(去掉文本中的空格)的字符串 格式 'P I C C'
 * @returns 去掉空格的文本 result 'PICC'
 */

export const emptySpacing = (str: string): string => {
  return str.replace(/ /g, '')
}

/***去除所有空格****/
export const trim = (str: string) => {
  return str.replace(/\s+/g, "");
}


// 根据 月 日 查看是什么星座
export const seachConstellationValue = (a: any, b: any) => {
  if (a == 1) {
      if (b <= 19 && b >= 1) {
          return('摩羯座')
      } else if (b <= 31 && b > 19) {
          return('水瓶座')
      } else {
          return('所选择的日期有误！');
      }
  }
  if (a == 2) {
      if (b <= 18 && b >= 1) {
          return('水瓶座');
      } else if (b <= 29 && b > 18) {
          return('双鱼座');
      } else {
          return('所选择的日期有误！');
      }
  }
  if (a == 3) {
      if (b <= 20 && b >= 1) {
          return('双鱼座');
      } else if (b <= 31 && b > 20) {
          return('白羊座');
      } else {
          return('所选择的日期有误！');
      }
  }
  if (a == 4) {
      if (b <= 19 && b >= 1) {
          return('白羊座');
      } else if (b <= 30 && b > 19) {
          return('金牛座');
      } else {
          return('所选择的日期有误！');
      }
  }
  if (a == 5) {
      if (b <= 20 && b >= 1) {
          return('金牛座');
      } else if (b <= 31 && b > 20) {
          return('双子座');
      } else {
          return('所选择的日期有误！');
      }
  }
  if (a == 6) {
      if (b <= 21 && b >= 1) {
          return('双子座');
      } else if (b <= 30 && b > 21) {
          return('巨蟹座');
      } else {
          return('所选择的日期有误！');
      }
  }
  if (a == 7) {
      if (b <= 22 && b >= 1) {
          return('巨蟹座');
      } else if (b <= 31 && b > 22) {
          return('狮子座');
      } else {
          return('所选择的日期有误！');
      }
  }
  if (a == 8) {
      if (b <= 22 && b >= 1) {
          return('狮子座');
      } else if (b <= 31 && b > 22) {
          return('处女座');
      } else {
          return('所选择的日期有误！');
      }
  }
  if (a == 9) {
      if (b <= 22 && b >= 1) {
          return('处女座');
      } else if (b <= 30 && b > 22) {
          return('天秤座');
      } else {
          return('所选择的日期有误！');
      }
  }
  if (a == 10) {
      if (b <= 23 && b >= 1) {
          return('天秤座');
      } else if (b <= 31 && b > 23) {
          return('天蝎座');
      } else {
          return('所选择的日期有误！');
      }
  }
  if (a == 11) {
      if (b <= 22 && b >= 1) {
          return('天蝎座');
      } else if (b <= 30 && b > 22) {
          return('射手座');
      } else {
          return('所选择的日期有误！');
      }
  }
  if (a == 12) {
      if (b <= 21 && b >= 1) {
          return('射手座');
      } else if (b <= 31 && b > 21) {
          return('摩羯座');
      } else {
          return('所选择的日期有误！');
      }
  }
}

// 全国省份列表
export const provinceList = () => {
  return [
    {city: '北京', value: '北京'},
    {city: '天津', value: '天津'},
    {city: '上海', value: '上海'},
    {city: '重庆', value: '重庆'},
    {city: '河北', value: '河北'},
    {city: '山西', value: '山西'},
    {city: '黑龙江', value: '黑龙江'},
    {city: '吉林', value: '吉林'},
    {city: '辽宁', value: '辽宁'},
    {city: '江苏', value: '江苏'},
    {city: '浙江', value: '浙江'},
    {city: '安徽', value: '安徽'},
    {city: '福建', value: '福建'},
    {city: '江西', value: '江西'},
    {city: '山东', value: '山东'},
    {city: '河南', value: '河南'},
    {city: '湖北', value: '湖北'},
    {city: '湖南', value: '湖南'},
    {city: '广东', value: '广东'},
    {city: '海南', value: '海南'},
    {city: '四川', value: '四川'},
    {city: '贵州', value: '贵州'},
    {city: '云南', value: '云南'},
    {city: '新疆', value: '新疆'},
    {city: '宁夏', value: '宁夏'},
    {city: '西藏', value: '西藏'},
    {city: '广西', value: '广西'},
    {city: '内蒙古', value: '内蒙古'},
    {city: '陕西', value: '陕西'},
    {city: '甘肃', value: '甘肃'},
    {city: '青海', value: '青海'},
  ]
}

// 汇率货币对应数据
export const exchangeList = () => {
  return [
    { code: 'USD', name: '美元' },
    { code: 'EUR', name: '欧元' },
    { code: 'JPY', name: '日元' },
    { code: 'GBP', name: '英镑' },
    { code: 'CAD', name: '加元' },
    { code: 'AUD', name: '澳元' },
    { code: 'HKD', name: '港元' },
    { code: 'CHF', name: '瑞郎' },
    { code: 'SGD', name: '新元' },
    { code: 'NZD', name: '新西兰元' },
    { code: 'CNY', name: '人民币' },
  ]
}

/**

* 将base64转换为文件

* @param dataurl base64格式数据

* @param filename 文件名

* @param filetype 文件类型

* @returns {File} 二进制流文件

*/

export function dataURLtoFile(dataurl: string, filename: string, filetype: string) {
  var arr = dataurl.split(','),
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], filename, {
    type: filetype
  })
}


// // 图片file转base64方法（file文件，回调函数）
export function fileToBase64(file: any, callback: any) {
  // 创建FileReader对象（不兼容IE）
  let reader = new FileReader()
  // 将file转为base64 （异步操作）
  reader.readAsDataURL(file)
  // 转换成功
  reader.onload = () => {
    const response = {
      status: true,
      data: reader.result
    }
    callback(response)
  }
  // 转换失败
  reader.onerror = function () {
    const response = {
      status: false,
      data: reader.error
    }
    callback(response)
  }
}

// 转base64码
export const getBase64 = (file: any) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    let fileResult: any = '';
    reader.readAsDataURL(file);
    reader.onload = () => {
      fileResult = reader.result
    };
    reader.onerror = (error) => {
      reject(error)
    };
    reader.onloadend = () => {
      resolve(fileResult)
    }
  })
}

// 压缩图片
import Compressor from 'compressorjs'

export const useCompressor = (file: any) => {
  return new Promise((resolve, reject) => {
    new Compressor(file, {
      //压缩质量, 0-1
      quality: 0.3,
      //转换的类型，默认为 image/png
      convertTypes: ['image/jpg'],
      //需要压缩的起始大小，默认5M, 5 * 1000 * 1000
      convertSize: 4000000,
      //压缩成功后处理
      success(result: any) {
        resolve(result)
      },
      error(err: any) {
        reject(err)
      }
    })
  })
}
// 用法：
// const uploadFileChange = (e: any, item: any, idx: number) => {
//   const _imgFile = e.target.files[0]
//   useCompressor(_imgFile).then((_imgFile: any) => {
//     const formData = new FormData()
//     formData.append('file', _imgFile)
//     formData.append('type', 'freight')
//     window.loading()
//     addImageStorage(formData).then((response) => {
//       window.loading(false)
//       if (response.status == '0') {
//         // deleteImg(3, item)
//         item.xingzhizhengbeimianImgObj = item.tracFileList[2] = {
//           fileUrl: response.data?.imageUrl,
//           fileType: '2_' + (idx + 1) + '_3',
//           fileId: '',
//           fileOperate: '1'
//         }
//       } else {
//         showToast(response.message)
//       }
//     })
//   })
// }

// 解析返回数据
export const parseResponse = (res: any) => {
  // 如果输入为空或 undefined，则返回 null
  if (!res) return null
  // 如果输入已经是对象，则直接返回
  if (typeof res !== 'string') return res
  try {
    // 尝试解码 URI 组件
    var json = decodeURIComponent(res)
    // 移除换行和空白字符
    json = json
      .replace(/\n/g, '')
      .replace(/\r/g, '')
      .replace(/\s|\xA0/g, '')
    // 尝试将字符串解析为 JSON 对象
    var jsonOK = JSON.parse(json)
    // 检查解析结果是否为对象，如果不是，返回 null
    if (typeof jsonOK === 'object' && jsonOK !== null) {
      return jsonOK
    } else {
      // 如果解析后的结果不是对象，直接返回原数据
      return res
    }
  } catch (error) {
    // 解析失败时直接返回原数据
    return res
  }
}

// 解决iOS客户端(安卓客户端正常) 返回不刷新的问题 
window.onpageshow = function (e) {
  if (e.persisted || (window.performance && window.performance.navigation.type == 2)) {
    window.location.reload() // 手动刷新
  }
}

//高德坐标转百度（传入经度、纬度）
export function bdEncrypt(gg_lng: any, gg_lat: any) {
  var X_PI = (Math.PI * 3000.0) / 180.0;
  var x = gg_lng,
    y = gg_lat;
  var z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * X_PI);
  var theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * X_PI);
  var bd_lng = z * Math.cos(theta) + 0.0065;
  var bd_lat = z * Math.sin(theta) + 0.006;
  return {
    bd_lat: bd_lat,
    bd_lng: bd_lng,
  };
}

// 获取图片宽高，并计算出图片的比例，同步返回
export const getImgSize = (imgSrc: any) => {
  return new Promise((resolve, reject) => {
    const img = new Image()
    img.src = imgSrc
    img.onload = function () {
      const width = img.width
      const height = img.height
      const ratio = width / height
      const obj = {
        width,
        height,
        ratio,
      }
      resolve(JSON.stringify(obj))
    }
    img.onerror = function (error) {
      reject(error)
    }
  })
}

/**
* 行状态 配合v-html使用
* <span v-html="onlineStatus(row.isEnable, row.beginTime, row.endTime)"></span>
*/

export function onlineStatus(
  state: string,
  startTime: string,
  endTime: string
) {
  const _startStamp = new Date(startTime).getTime()
  const _endStamp = new Date(endTime).getTime()
  const _curStamp = new Date().getTime()
  let _word = ''
  switch (state) {
    case 'Y':
      if (_curStamp < _startStamp) {
        _word = '<p style="color:#3772F6">未开始</p>'
      } else if (_curStamp > _endStamp) {
        _word = '<p style="color:rgb(189, 0, 0)">已过期</p>'
      } else {
        _word = '<p style="color:#3772F6">上线</p>'
      }
      break
    case 'N':
      _word = '<p style="color:rgb(189, 0, 0)">下线</p>'
      break
    default:
      _word = '--'
      break
  }
  return _word
}

export function deepClone(obj: any) {
  return JSON.parse(JSON.stringify(obj));
}

// 获取滚动条距离顶端的距离
export function getScrollTop() {
  var scrollPos;
  if (window.pageYOffset) {
      scrollPos = window.pageYOffset;
  }
  else if (document.compatMode && document.compatMode != 'BackCompat') { scrollPos = document.documentElement.scrollTop; }
  else if (document.body) { scrollPos = document.body.scrollTop; }
  return scrollPos;
}

// 计算时间相差天数
export function GetNumberOfDays(date1: any,date2: any) { // 获得天数
  var a1 = Date.parse(new Date(date1));
  var a2 = Date.parse(new Date(date2));
  var day = parseInt((a2-a1)/ (1000 * 60 * 60 * 24)); // 核心：时间戳相减，然后除以天数
  return day
}

// 指定位置的字符串替换
export function replacepos(text: any,start: any,stop: any,replacetext: any) {
  var mystr = text.substring(0,start)+replacetext+text.substring(stop);
  return mystr;
}

// 数组去重arr数组 val根据某个属性去重
export function unique(arr: any, val: any) {
  const res = new Map();
  return arr.filter((item: any) => !res.has(item[val]) && res.set(item[val], 1));
}

// 移动端 touch事件模拟点击事件
export function addClickEvent({node, fun}: any) {
  var xArr = []; // 存放横坐标
  var yArr = []; // 存放纵坐标
  node.addEventListener("touchstart", function(e) { 
      //手指触摸屏幕的时候清空两个数组
      xArr.length = 0;
      yArr.length = 0;
  }); 

  node.addEventListener("touchmove",function(e) {
      //如果滑动了屏幕，xArr和yArr将各存入两个坐标值，即始末坐标值
      xArr.push(e.targetTouches[0].pageX);
      yArr.push(e.targetTouches[0].pageY);
  });

  node.addEventListener('touchend',function(e) {
      var far;
      var flag = true;
      //计算平移距离，区分滑动事件和点击事件
      if((xArr.length > 1) && (yArr.length > 1)) {
          far = (Math.abs(xArr[0]-xArr[1]))^2 + (Math.abs(yArr[0]-yArr[1]))^2;
          if(far > 0){
              flag = false;
          }
      }
      if(flag) {
          fun(e)
      }
  })
}

//http转https
export function addHttps(url: any) {
  let tel;
  if(document.location.protocol=='https:'){
      tel = url.replace('http:','https:')
  }else if('http:' == document.location.protocol){
      tel = url.replace('https:','http:')
  }
  return tel
}

/**
 * 图片url链接转base64
 * @param {String} url 图片链接
 * @returns 转base64后的值或者报错信息
 */
export function imgUrlToBase64(url: any, options={}) {
  return new Promise((resolve, reject) => {
      if (!url) {
          reject("请传入url内容");
      }
      // if (/\.(png|jpe?g|gif|svg)(\?.*)?$/.test(url)) {
          // 图片地址
          const image = new Image();
          // 设置跨域问题
          image.setAttribute("crossOrigin", "anonymous");
          // 图片地址
          image.src = url;
          image.onload = () => {
              const canvas = document.createElement("canvas");
              const ctx = canvas.getContext("2d");
              let width = image.width;
              let height = image.height;
              var max = options.maxSize || 1000; // 默认最大值为1024px
              var rate = 1;
              if(options.sizeType == 'compressed'){
                  if(width > max || height > max){
                      rate = width > height ? max/width : max/height
                  }
              }
              canvas.width = width*rate;
              canvas.height = height*rate;
              ctx.drawImage(image,0,0,width,height,0,0,width*rate,height*rate);
              // ctx.drawImage(image, 0, 0, image.width, image.height);
              // 获取图片后缀
              const ext = url.substring(url.lastIndexOf(".") + 1).toLowerCase();
              
              // 转base64
              const dataUrl = canvas.toDataURL(`image/${ext}`);
              // console.log(dataUrl)
              try {
                  console.log(ext,rate,countKB(dataUrl).toFixed(2),'KB','转base642',width,height,width*rate,height*rate)
              } catch (error) {
                  console.log(error,'error')
                  console.log(ext,rate,dataUrl.length,'转base642',width,height,width*rate,height*rate)
              }
              resolve(dataUrl || "");
          };
          image.onerror = (err) => {
              reject(err);
          };
      // } else {
      //     // 非图片地址
      //     reject("非(png/jpe?g/gif/svg等)图片地址");
      // }
  })
}

/**
 * 读取图片（或文件）转成base64
 * @param {Object} file 图片文件的file，一般是文件上传的file信息
 * @returns 转base64后的base64图片地址，或错误信息
 */
export function readImgToBase64(file: any) {
  return new Promise((resolve, reject) => {
    try {
      // 读取信息
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
        // 转base64结果
        const base64Url = reader.result;
        resolve(base64Url);
      };

      reader.onerror = (err) => {
        reject(err);
      };
    } catch (error) {
      reject(error);
    }
  });
}

// // 截屏相关？
// import html2canvas from "html2canvas";

// export function clickGeneratePicture(copyDom) {
//   let imgUrl = '';
//   var width = copyDom.offsetWidth; //dom宽
//   var height = copyDom.offsetHeight; //dom高
//   var scale = 1; //放大倍数
//   var canvas = document.createElement("canvas");
//   canvas.width = width * scale; //canvas宽度
//   canvas.height = height * scale; //canvas高度
//   return new Promise((resolve,reject) => {
//     html2canvas(copyDom, {
//       scale: scale,
//       canvas: canvas,
//       width: width,
//       heigth: height,
//       backgroundColor: null,
//       dpi:window.devicePixelRatio,
//     })
//       .then(function(canvas) {
//         imgUrl = canvas.toDataURL("image/png");
//         resolve(imgUrl);
//       })
//       .catch((err) => {
//           reject('')
//       });
//   });
// }

function countKB(str: string) {
  // 将字符串转换为UTF-8编码的字节数组
  const utf8Bytes = new TextEncoder().encode(str);
  // 计算字节数组的长度
  const byteLength = utf8Bytes.length;
  // 将字节长度转换为KB
  const sizeInKB = byteLength / 1024;
  return sizeInKB;
}

//获取URL 链接 中的参数
export const GetUrlPara = (str: string) => {
  const reg = new RegExp('(^|&)' + str + '=([^&]*)(&|$)');
  const r = window.location.search.substr(1).match(reg);
  if (r != null) {
      return decodeURIComponent(r[2]);
  }
  return null;
}

// base64图片旋转90度
// 调用： let img = await rotateBase64Img(imgUrl, -90)
export const rotateBase64Img =(src: any, edg: any) => {
  return new Promise((resolve, redirect)=>{
    try {
    var canvas = document.createElement("canvas")
    var ctx = canvas.getContext("2d")
    var imgW // 图片宽度
    var imgH // 图片高度
    var size // canvas初始大小
    if (edg % 90 != 0) {
        console.error("旋转角度必须是90的倍数!");
        throw '旋转角度必须是90的倍数!';
    }
    (edg < 0) && (edg = (edg % 360) + 360)
    const quadrant = (edg / 90) % 4; //旋转象限
    const cutCoor = {sx: 0, sy: 0, ex: 0, ey: 0}; // 裁剪坐标
    var image = new Image()
    image.crossOrigin = "anonymous"
    image.src = src;
    image.onload = function () {
        imgW = image.width;
        imgH = image.height;
        size = imgW > imgH ? imgW : imgH;
        canvas.width = size * 2;
        canvas.height = size * 2;
        switch (quadrant) {
            case 0:
                cutCoor.sx = size;
                cutCoor.sy = size;
                cutCoor.ex = size + imgW;
                cutCoor.ey = size + imgH;
                break;
            case 1:
                cutCoor.sx = size - imgH;
                cutCoor.sy = size;
                cutCoor.ex = size;
                cutCoor.ey = size + imgW;
                break;
            case 2:
                cutCoor.sx = size - imgW;
                cutCoor.sy = size - imgH;
                cutCoor.ex = size;
                cutCoor.ey = size;
                break;
            case 3:
                cutCoor.sx = size;
                cutCoor.sy = size - imgW;
                cutCoor.ex = size + imgH;
                cutCoor.ey = size + imgW;
                break;
        }
        ctx.translate(size, size);
        ctx.rotate(edg * Math.PI / 180);
        ctx.drawImage(image, 0, 0);
        var imgData = ctx.getImageData(cutCoor.sx, cutCoor.sy, cutCoor.ex, cutCoor.ey);
        if (quadrant % 2 == 0) {
            canvas.width = imgW;
            canvas.height = imgH;
        } else {
            canvas.width = imgH;
            canvas.height = imgW;
        }
        ctx.putImageData(imgData, 0, 0);
        resolve(canvas.toDataURL("image/png"))
      }
    } catch (error) {
      console.log('err: '+error,src?.length,edg)
      redirect(error)
    }
  })
}
